package com.innovation.ic.cyz.base.handler;

import com.innovation.ic.cyz.base.pojo.annotation.Description;
import lombok.var;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 枚举工具类
 */
public class EnumHandler extends AbstractHandler {

    /**
     * 获取枚举值的描述
     */
    public static <T> String getDescription(T t, int value) throws IllegalAccessException {
        Field[] fields = t.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return "";
        }
        String result = "";
        for (Field field : fields) {
            int fieldValue = field.getInt(t);
            if (fieldValue == value) {
                var description = field.getAnnotation(Description.class);
                if (description != null) {
                    result = description.context();
                }
                break;
            }
        }
        return result;
    }

    /**
     * 获取枚举值的描述
     */
    public static <T> Map<Integer, String> getDescriptions(T t) throws IllegalAccessException {
        Map<Integer, String> map = new HashMap<>();
        Field[] fields = t.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return map;
        }
        for (Field field : fields) {
            int fieldValue = field.getInt(t);
            var description = field.getAnnotation(Description.class);
            if (description != null) {
                map.put(fieldValue, description.context());
            }
        }
        return map;
    }

}
